package com.yuqing.sentimentapp.home.acitivity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.linkface.baselibrary.utils.DensityUtil;
import com.linkface.common.adaper.CommonViewHolder;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.home.fragment.HomeFragment;
import com.yuqing.sentimentapp.home.bean.HotChannelBean;
import com.yuqing.sentimentapp.home.presenter.YqSearchPresenter;
import com.yuqing.sentimentapp.home.presenter.impl.YqSearchListPresenterImpl;
import com.yuqing.sentimentapp.home.view.SearchView;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.widget.FlowLayout;
import com.yuqing.sentimentapp.widget.jzvideo.Jzvd;
import com.yuqing.sentimentapp.widget.xrecyclerview.XRecyclerView;
import com.yuqing.sentimentapp.yqlist.activity.YuQingDetailActivity;
import com.yuqing.sentimentapp.yqlist.adapter.YqListAdapter;
import com.yuqing.sentimentapp.yqlist.bean.YqListResultBean;
import com.yuqing.sentimentapp.yqlist.bean.YuQingDataBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ShenHe on 2019/3/30.
 */

public class SearchActivity extends BaseActivity implements SearchView<YqListResultBean> {

    @BindView(R.id.flowLayout)
    FlowLayout mFlowLayout;
    @BindView(R.id.flowLayout_channel)
    FlowLayout mFlowLayoutChannel;
    @BindView(R.id.et_search)
    EditText mEtSearch;
    @BindView(R.id.iv_clear)
    ImageView mIvClear;
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;
    @BindView(R.id.tv_cancle)
    TextView mTvCancle;
    @BindView(R.id.tv_no_history)
    TextView mTvNoHistory;
    @BindView(R.id.tv_no_hot_channel)
    TextView mTvNoHotChannel;
    @BindView(R.id.layout_recycler)
    FrameLayout mLayoutRecycler;
    @BindView(R.id.recyclerView)
    XRecyclerView mRecyclerView;
    private YqSearchPresenter mPresenter;
    private YqListAdapter mAdapter;
    private List<YuQingDataBean> dataList = new ArrayList<>();
    private int page = 1;
    private String searchHistoryData;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void initPresenter() {
        mPresenter = new YqSearchListPresenterImpl(this);
    }

    @Override
    public void initView() {
        initListener();
        initHistoryData();
        initChannelData();
        initRecyclerView();
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setLoadingMoreEnabled(true);
        mRecyclerView.setPullRefreshEnabled(false);

        mAdapter = new YqListAdapter(this, dataList, new CommonViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(int position) {
                YuQingDetailActivity.start(SearchActivity.this, dataList.get(position - 1).getBdArticleId(), position - 1);
                dataList.get(position - 1).setIsRead("1");
                mAdapter.notifyItemChanged(position);
            }

            @Override
            public void onItemLongClickListener(int position) {

            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                page++;
                loadSearchData(page, mEtSearch.getText().toString().trim());
            }
        });
        mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                Jzvd jzvd = view.findViewById(R.id.videoplayer);
                if (jzvd != null && Jzvd.CURRENT_JZVD != null &&
                        jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                    if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                        Jzvd.resetAllVideos();
                    }
                }
            }
        });

//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    Glide.with(mContext).resumeRequests();
//                }else {
//                    Glide.with(mContext).pauseRequests();
//                }
//            }
//        });
    }

    private void loadSearchData(int page, String keyword) {
        mPresenter.loadYqSearchListData(page, 10, keyword);
    }

    private void initListener() {
        mEtSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {

                String keytag = mEtSearch.getText().toString().trim();

                if (TextUtils.isEmpty(keytag)) {
                    ToastUtil.showShort("请输入搜索关键字");
                    return false;
                }

                dataList.clear();
                mAdapter.notifyDataSetChanged();
                SharePrefrenceHelper.setSearchHistoryData(searchHistoryData + ";" + keytag);
                mLayoutRecycler.setVisibility(View.VISIBLE);
                // 搜索功能主体
                page = 1;
                mPresenter.loadYqSearchListData(page, 10, keytag);
                return true;
            }
            return false;
        });
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mEtSearch.getText().toString().trim())) {
                    mLayoutRecycler.setVisibility(View.GONE);
                    mIvDelete.setVisibility(View.GONE);
                    initHistoryData();
                } else {
                    mIvDelete.setVisibility(View.VISIBLE);
                }
            }
        });
        mIvDelete.setOnClickListener(v -> mEtSearch.setText(""));
    }

    private void initHistoryData() {
        searchHistoryData = SharePrefrenceHelper.getSearchHistoryData();
        if (TextUtils.isEmpty(searchHistoryData)) {
            mTvNoHistory.setVisibility(View.VISIBLE);
            return;
        } else {
            mTvNoHistory.setVisibility(View.GONE);
        }
        updateHistoryView();
    }

    private void updateHistoryView() {
        mFlowLayout.removeAllViews();
        String[] searchStrings = searchHistoryData.split(";");
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 0;
        lp.rightMargin = DensityUtil.dip2px(this,15);
        lp.topMargin = 0;
        lp.bottomMargin = DensityUtil.dip2px(this,10);
        for (int i = 0; i < searchStrings.length; i++) {
            if (TextUtils.isEmpty(searchStrings[i])) continue;
            TextView textView = new TextView(this);
            textView.setText(searchStrings[i]);
            textView.setTextSize(13);
            textView.setTextColor(getResources().getColor(R.color.color_333333));
            textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.flow_txt_bg));
            int finalI = i;
            textView.setOnClickListener(v -> {
                mLayoutRecycler.setVisibility(View.VISIBLE);
                mPresenter.loadYqSearchListData(1, 10, searchStrings[finalI]);
            });
            mFlowLayout.addView(textView,lp);
        }
    }

    private void initChannelData() {
        mPresenter.loadHotChanneltData();
    }

    private void updateHotChannelView(List<HotChannelBean.DataBean> dataBeans) {
        if (dataBeans == null || dataBeans.size() <= 0) {
            mTvNoHotChannel.setVisibility(View.VISIBLE);
            return;
        } else {
            mTvNoHotChannel.setVisibility(View.GONE);
        }
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 0;
        lp.rightMargin = DensityUtil.dip2px(this,15);
        lp.topMargin = 0;
        lp.bottomMargin = DensityUtil.dip2px(this,10);
        for (int i = 0; i < dataBeans.size(); i++) {
            TextView textView = new TextView(this);
            textView.setText(dataBeans.get(i).getName());
            textView.setTextSize(13);
            textView.setTextColor(getResources().getColor(R.color.color_333333));
            textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.flow_txt_bg2));
            int finalI = i;
            textView.setOnClickListener(v -> {
                Intent intent = new Intent();
                intent.putExtra(HomeFragment.RESULT_CHANNEL_DATA, dataBeans.get(finalI));
                setResult(HomeFragment.RESULT_CODE_SEARCH, intent);
                finish();
            });
            mFlowLayoutChannel.addView(textView,lp);
        }
    }

    @OnClick({R.id.tv_cancle, R.id.iv_clear})
    public void onClick(View view) {
        switch (view.getId()) {
            default:
                break;
            case R.id.tv_cancle:
                finish();
                break;
            case R.id.iv_clear:
                String search = SharePrefrenceHelper.getSearchHistoryData();
                if (TextUtils.isEmpty(search)) return;
                searchHistoryData = "";
                SharePrefrenceHelper.setSearchHistoryData("");
                mFlowLayout.removeAllViews();
                mTvNoHistory.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void stopLoad() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
    }

    @Override
    public void returnHotChannelResult(HotChannelBean hotChannelBean) {
        if (hotChannelBean == null) return;
        List<HotChannelBean.DataBean> data = hotChannelBean.getData();
        updateHotChannelView(data);
    }

    @Override
    public void returnSearchListResult(YqListResultBean result) {
        stopLoad();
        if (result == null) return;
        List<YuQingDataBean> data = result.getData();
        if (data == null || data.size() <= 0) {
            mRecyclerView.setNoMore(true);
            return;
        }
        dataList.addAll(data);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSuccess(YqListResultBean data) {
        stopLoad();
    }

    @Override
    public void onFailure(String message) {
        stopLoad();
        ToastUtil.showShort(message);
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.resetAllVideos();
    }
}
